package com.ai_daily.aitiantian.util;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.webkit.WebSettings;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.ai_daily.aitiantian.base.BaseApp;
import com.baidu.speech.utils.LogUtil;

import java.util.List;
import java.util.Locale;


public class AppUtils {

    private static String sUserAgent;
    public static final String APP_USER_AGENT_PATTERN = " (guohui_app; Android/%s/%d)";
    /**
     * 重启应用程序
     */
    public static void restartApp(Context activity) {
        restartApp(activity, false);
    }

    /**
     * 重启应用程序
     *
     * @param isFull 是否重新初始化Application
     */
    public static void restartApp(Context activity, boolean isFull) {
        Intent intent = BaseApp.getInstance().getPackageManager().getLaunchIntentForPackage(activity.getPackageName());
        if (intent != null) {
            if (isFull) {
                // 整体重启，冷启动，临时数据清空。
//                PendingIntent restartIntent = PendingIntent.getActivity(activity, 0, intent, PendingIntent.FLAG_ONE_SHOT);
//                AlarmManager mgr = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
//                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200, restartIntent);
                android.os.Process.killProcess(android.os.Process.myPid());
            } else {
                // 软件重启，清activity栈，不清Application。
                //| Intent.FLAG_ACTIVITY_CLEAR_TASK  语言切换时出现白屏，目前去掉这句  8.8
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                intent.putExtra(SHOW_AD_FLAG, false);
                activity.startActivity(intent);
            }
        }
    }

    /**
     * 判断应用是否在运行
     *
     * @param context
     * @return
     */
    public static boolean isAppRunning(Context context, String applicationId) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;

        //100表示取的最大的任务数，info.topActivity表示当前正在运行的Activity，info.baseActivity表系统后台有此进程在运行
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(applicationId) || info.baseActivity.getPackageName().equals(applicationId)) {
                isAppRunning = true;
                LogUtil.i("ActivityService isRun()", info.topActivity.getPackageName() + " info.baseActivity.getPackageName()=" + info.baseActivity.getPackageName());
                break;
            }
        }
        LogUtil.i("ActivityService isRun()", applicationId + " 程序  ...isAppRunning......" + isAppRunning);
        return isAppRunning;
    }

    /**
     * 获取版本名称，即AndroidManifest.xml中的android:versionName的值
     *
     * @param context context
     * @return versionName
     */
    public static String getVersion(Context context) {
        if (context == null) {
            return null;
        }
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取版本名称，即AndroidManifest.xml中的android:versionCode的值
     *
     * @param context context
     * @return versionCode
     */
    public static long getVersionCode(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                return packageInfo.getLongVersionCode();
            } else {
                return packageInfo.versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static void showToast(final Context context, final String toastStr) {
        Toast toast = Toast.makeText(context.getApplicationContext(), toastStr, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 400);
        toast.show();
    }

    public static void showToast(final Context context, final int toastId) {
        Toast toast = Toast.makeText(context.getApplicationContext(), context.getString(toastId), Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 400);
        toast.show();
    }

    //跳转应用市场下载
    public static void goToMarket(Context context, String packageName) {
        try {
            Uri uri = Uri.parse("market://details?id=" + packageName);
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
            goToMarket.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("https://m-console.ciftis.org/download"));
            context.startActivity(intent);
        }
    }

    /**
     * 是否安装
     *
     * @param context context
     * @param pkgName context
     * @return 是否安装
     */
    public static boolean isInstallApp(Context context, String pkgName) {
        final PackageManager packageManager = context.getPackageManager();
        @SuppressLint("QueryPermissionsNeeded") List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); ++i) {
                String pn = pinfo.get(i).packageName.toLowerCase(Locale.ENGLISH);
                if (TextUtils.equals(pn, pkgName)) {
                    return true;
                }
            }
        }
        return false;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static String getUserAgent(Context context) {
        String userAgent = "";
        try {
            userAgent = WebSettings.getDefaultUserAgent(BaseApp.getInstance());
        } catch (Exception e) {
            userAgent = System.getProperty("http.agent");
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        if (sUserAgent == null) {
            sUserAgent = String.format(Locale.CANADA, APP_USER_AGENT_PATTERN, getVersion(context), getVersionCode(context));
        }
        return sb.append(sUserAgent).toString();
    }
}
